package com.itcast.demo.demo;

/**
 * 编写Java  Application 程序，查找出字符串str中字符A，替换成字符B，
 * 并统计替换的次数。【注】不可以使用Java的内置函数，如index()、replace()等。
 *
 * @author zheng.zhang
 */
public class Test1 {

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        test1.replaceStr("dsafanfvapdifiaiogfa", 'a', 'b');
    }

    /**
     * 字符串替换
     *
     * @param str 字符串
     * @param A   字符A
     * @param B   字符B
     */
    public void replaceStr(String str, char A, char B) {
        if (str == null || str.isEmpty()) {
            return;
        }
        // 统计A字符出现的次数
        int count = 0;
        // 替换后的字符串
        StringBuilder sb = new StringBuilder();
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (A == c) {
                chars[i] = B;
                count++;
            }
            sb.append(chars[i]);
        }
        System.out.println("Result String: " + sb.toString());
        System.out.println("A count: " + count);
    }
}
